package com.cdtye.shuoh.config.gb28181.zlm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * zlmediakit http调用工具类
 */
@Component
@ConditionalOnProperty(value = "sip.enabled", havingValue = "true")
public class ZLMRESTfulUtils {

    private final static Logger logger = LoggerFactory.getLogger(ZLMRESTfulUtils.class);

    @Value("${media.ip}")
    private String mediaIp;

    @Value("${media.port}")
    private int mediaPort;

    @Value("${media.secret}")
    private String mediaSecret;

    /**
     * 发送http请求 详情见（https://github.com/zlmediakit/ZLMediaKit/wiki/MediaServer%E6%94%AF%E6%8C%81%E7%9A%84HTTP-API）
     * @param api ('/index/api/addFFmpegSource',/index/api/getMediaInfo,...)
     * @param param 参数
     * @return
     */
    public JSONObject sendPost(String api, Map<String, Object> param) {
        OkHttpClient client = new OkHttpClient();
        String url = String.format("http://%s:%s/index/api/%s",  mediaIp, mediaPort, api);
        JSONObject responseJSON = null;
        logger.debug(url);

        FormBody.Builder builder = new FormBody.Builder();
        builder.add("secret",mediaSecret);
        if (param != null) {
            for (String key : param.keySet()){
                builder.add(key, param.get(key).toString());
            }
        }

        FormBody body = builder.build();
        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseStr = response.body().string();
                if (responseStr != null) {
                    responseJSON = JSON.parseObject(responseStr);
                }
            }
        } catch (ConnectException e) {
            logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
            logger.info("请检查media配置并确认ZLM已启动...");
        }catch (IOException e) {
            e.printStackTrace();
        }

        logger.info("zlmConfig",responseJSON);
        return responseJSON;
    }

    /**
     * 获取流列表，可选筛选参数
     * @param app
     * @param schema 筛选协议，例如 rtsp或rtmp
     * @return 筛选应用名，例如 live
     */
    public JSONObject getMediaList(String app, String schema){
        Map<String, Object> param = new HashMap<>();
        param.put("app",app);
        param.put("schema",schema);
        param.put("vhost","__defaultVhost__");
        return sendPost("getMediaList",param);
    }

    /**
     * 获取流相关信息
     * @param app
     * @param schema
     * @param stream
     * @return
     */
    public JSONObject getMediaInfo(String app, String schema, String stream){
        Map<String, Object> param = new HashMap<>();
        param.put("app",app);
        param.put("schema",schema);
        param.put("stream",stream);
        param.put("vhost","__defaultVhost__");
        return sendPost("getMediaInfo",param);
    }

    /**
     * 获取rtp代理时的某路ssrc rtp信息
     * @param stream_id 获取rtp代理时的某路ssrc rtp信息
     * @return
     */
    public JSONObject getRtpInfo(String stream_id){
        Map<String, Object> param = new HashMap<>();
        param.put("stream_id",stream_id);
        return sendPost("getRtpInfo",param);
    }

    public JSONObject addFFmpegSource(String src_url, String dst_url, String timeout_ms){
        System.out.println(src_url);
        System.out.println(dst_url);
        Map<String, Object> param = new HashMap<>();
        param.put("src_url", src_url);
        param.put("dst_url", dst_url);
        param.put("timeout_ms", timeout_ms);
        return sendPost("addFFmpegSource",param);
    }

    public JSONObject delFFmpegSource(String key){
        Map<String, Object> param = new HashMap<>();
        param.put("key", key);
        return sendPost("delFFmpegSource",param);
    }

    /**
     *获取服务器配置
     * @return
     */
    public JSONObject getMediaServerConfig(){
        return sendPost("getServerConfig",null);
    }

    /**
     * 设置服务器配置
     * @param param
     * @return
     */
    public JSONObject setServerConfig(Map<String, Object> param){
        return sendPost("setServerConfig",param);
    }

    /**
     * 创建GB28181 RTP接收端口，如果该端口接收数据超时，则会自动被回收(不用调用closeRtpServer接口)
     * @param param
     * @return
     */
    public JSONObject openRtpServer(Map<String, Object> param){
        return sendPost("openRtpServer",param);
    }

    /**
     * 关闭GB28181 RTP接收端口
     * @param param
     * @return
     */
    public JSONObject closeRtpServer(Map<String, Object> param) {
        return sendPost("closeRtpServer",param);
    }

    /**
     *
     * @param flvUrl 需要截图的url，可以是本机的，也可以是远程主机的（eg:http://192.168.1.8:80/rtp/06147ACB.live.flv）
     * @param timeout_sec 截图失败超时时间，防止FFmpeg一直等待截图
     * @param expire_sec 截图的过期时间，该时间内产生的截图都会作为缓存返回
     */
    public byte[] getSnap(String flvUrl, int timeout_sec, int expire_sec) {
        Map<String, Object> param = new HashMap<>(3);
        param.put("url", flvUrl);
        param.put("timeout_sec", timeout_sec);
        param.put("expire_sec", expire_sec);
        return sendPostForImg("getSnap", param);
    }

    /**
     * 发送请求图片请求
     * @param api getSnap
     * @param params
     * @return
     */
    private byte[] sendPostForImg(String api, Map<String, Object> params) {
        OkHttpClient client = new OkHttpClient();
        String url = String.format("http://%s:%s/index/api/%s",  mediaIp, mediaPort, api);
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("secret",mediaSecret);
        if (params != null) {
            for (String key : params.keySet()){
                builder.add(key, params.get(key).toString());
            }
        }

        FormBody body = builder.build();

        System.out.println("++++++++++++"+url);

        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).bytes();
            } else {
                logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
            }
        } catch (ConnectException e) {
            logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
            logger.info("请检查media配置并确认ZLM已启动...");
        } catch (IOException e) {
            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
        }
        return null;
    }
}
